{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use the retry module or similar alternatives.\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-698ada706af1>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于没有类似gridSearchCV这样的功能，就直接手动修改参数寻找合适的值，以下是最后的结果：\n",
    "\n",
    "隐层：一共采用了三层隐层，分别是500,400,300个神经元\n",
    "\n",
    "参数初始值：一开始是全0，后来发现无法进行迭代，就换成了随机数，但这样一开始似乎梯度很大，需要很低的学习率才能避免梯度爆炸，于是最后改成了高斯分布下的随机数\n",
    "\n",
    "学习率：依照观察结果，到后面经常出现震荡，就用了带衰减的学习率\n",
    "\n",
    "正则：采用l1正则时会出现nan的情况，原因还不清楚，后改用L2\n",
    "\n",
    "激活函数：各层都采用ReLU\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "#neuron num\n",
    "nn1 = 500\n",
    "nn2 = 400\n",
    "nn3 = 300\n",
    "lamda = 0.00001 #正则超参数\n",
    "learning_rate_ = 0.8\n",
    "learning_rate_decay = 0.95\n",
    "lord = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W1 = tf.Variable(tf.truncated_normal(shape=[784, nn1],stddev=0.1))\n",
    "b1 = tf.Variable(tf.constant(0.1, shape=[nn1]))\n",
    "logits1 = tf.matmul(x, W1) + b1\n",
    "L1 = tf.nn.relu(logits1)\n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([nn1, nn2],stddev=0.01))\n",
    "b2 = tf.Variable(tf.constant(0.1, shape=[nn2]))\n",
    "logits2 = tf.matmul(L1, W2) + b2\n",
    "L2 = tf.nn.relu(logits2)\n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([nn2, nn3],stddev=0.01))\n",
    "b3 = tf.Variable(tf.constant(0.1, shape=[nn3]))\n",
    "logits3 = tf.matmul(L2, W3) + b3\n",
    "L3 = tf.nn.relu(logits3)\n",
    "\n",
    "W4 = tf.Variable(tf.truncated_normal([nn3, 10],stddev=0.01))\n",
    "b4 = tf.Variable(tf.constant(0.1, shape=[10]))\n",
    "\n",
    "y = tf.matmul(L3, W4) + b4\n",
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)\n",
    ")+lamda*tf.norm(W1,ord=lord)+lamda*tf.norm(W2,ord=lord)+lamda*tf.norm(W3,ord=lord)+lamda*tf.norm(W4,ord=lord)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "global_step = tf.Variable(0)\n",
    "learning_rate = tf.train.exponential_decay(learning_rate_,global_step,100,learning_rate_decay,staircase=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy,global_step=global_step)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.289573\n",
      "0.0892\n",
      "0.096808754\n",
      "0.9221\n",
      "0.046441674\n",
      "0.9499\n",
      "0.017695995\n",
      "0.9659\n",
      "0.038762275\n",
      "0.9653\n",
      "0.03206655\n",
      "0.9703\n",
      "0.018058423\n",
      "0.9734\n",
      "0.005767821\n",
      "0.9755\n",
      "0.012807062\n",
      "0.9778\n",
      "0.006187472\n",
      "0.978\n",
      "0.0062882113\n",
      "0.979\n",
      "0.004893847\n",
      "0.9801\n",
      "0.004503848\n",
      "0.9814\n",
      "0.057641953\n",
      "0.9805\n",
      "0.0024155886\n",
      "0.9815\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    batch_xs = batch_xs\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    if i %200 == 0:\n",
    "        now_cross_entropy = sess.run(cross_entropy,feed_dict={x: batch_xs,y_: batch_ys})\n",
    "        print(now_cross_entropy)\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9818\n"
     ]
    }
   ],
   "source": [
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
